﻿using DBToExcel.Model;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;

namespace DBToExcel.Code
{
    public class DBConnUtils
    {
        /// <summary>
        /// 测试连接
        /// </summary>
        /// <param name="conn"></param>
        /// <returns></returns>
        public static string TestConn(MDBConn conn) {
            string result=string.Empty;
            if (conn == null)
            {
                result="连接信息不能为空";
                return result;
            }

            if (string.IsNullOrEmpty(conn.ClassName))
            {
                result = "连接类名不能为空";
                return result;
            }

            if (string.IsNullOrEmpty(conn.FileName))
            {
                result="驱动类型不能为空";
                return result;
            }

            if (string.IsNullOrEmpty(conn.ConnStr))
            {
                result = "连接字符串不能为空";
                return result;
            }

            IDbConnection connection = null;
            try
            {
                connection = GetConn(conn.FileName, conn.ClassName, conn.ConnStr);
            }
            catch (Exception ex)
            {

                result="连接数据库失败：" + ex.Message;
            }
            finally
            {
                if (connection != null)
                {
                    connection.Close();
                }
            }

            return result;
        }

        /// <summary>
        /// 获取连接
        /// </summary>
        /// <param name="driver"></param>
        /// <param name="className"></param>
        /// <param name="connStr"></param>
        /// <returns></returns>
        public static IDbConnection GetConn(string driver, string className, string connStr) {
            IDbConnection connection = Activator.CreateInstance(Assembly.LoadFrom(driver).GetType(className)) as IDbConnection;
            connection.ConnectionString = connStr;
            connection.Open();
            return connection;
        }
    }
}
